import { useCallback, useEffect, useState } from 'react';
import { ReactSortable } from 'react-sortablejs';
import clsx from 'clsx';

import { CustomDrawer } from '@/components/CustomDrawer/CustomDrawer';
import { GripVertical, Plus } from 'lucide-react';
import { TaskCard } from '@/components/TaskCard/TaskCard';
import { NewTaskButton } from '@/components/NewTask';
import { AlertAnswer, DialogInput, TextArea } from '@/components/Customs';
import { Button } from '@/components/ui/button';
import useFetchColumns from '@/hook/useColumns';
import { iterable } from '@/helpers';
import { TrashIcon } from '@/components/Icons';
import { useAppDispatch } from '@/hook/useRedux';
import { deleteColumn, renameColumn, setRenameColumn } from '@/redux/columns/columnsSLice';
import useInputFocusContext from '@/context/InputFocusContext';

interface Props {
  className?: string;
}

export const BoardContent = ({ className, }: Props) => {
  const [data, setData] = useState<Task | null>(null);
  const [open, setOpen] = useState(false);
  const [openCreateColumn, setOpenCreateColumn] = useState(false);
  const [removeColumn, setRemoveColumn] = useState<number | null>(null);
  const [removeColumnName, setRemoveColumnName] = useState<string | null>(null);

  const { columns, status, handleSortColumns, moveTaskItem, moveTaskItemColumn, onAddNewColumn } = useFetchColumns()

  const handleClose = () => setOpen(false);

  const dispatch = useAppDispatch()

  const handleOpen = useCallback((task: Task) => {
    setOpen(true);
    setData(task);
  }, []);

  const onSubmit = (value: string) => {
    onAddNewColumn(value);
    setOpenCreateColumn(false)
  };

  const handleAddColumn = () => {
    setOpenCreateColumn(true)
    focusInput('NewColumnInBoard')
  }

  const handleRemoveColumn = () => {
    if (removeColumn) {
      dispatch(deleteColumn(removeColumn));
      setRemoveColumn(null);
      setTimeout(() => { setRemoveColumnName(null); }, 500);
    }
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>, columnId: number) => {
    dispatch(setRenameColumn({ name: e.target.value, id: columnId }));
  };

  const onColumnSaveName = (e: React.ChangeEvent<HTMLTextAreaElement>, columnId: number) => {
    dispatch(renameColumn({ name: e.target.value, columnId }))
  }

  useEffect(() => {

    return () => {
      setOpen(false);
      setData(null);
    }
  }, [status])


  const { focusInput } = useInputFocusContext();

  if (status === 'loading') {
    return <div>Loading...</div>;
  }

  return (
    <div className={clsx(className, 'board flex w-full gap-10 p-2 overflow-y-auto')}>
      {data && <CustomDrawer anchor='right' open={open} onClose={handleClose} data={data.id} />}
      {columns?.length ? (<>
        <ReactSortable
          ghostClass='subElement'
          easing='linear'
          dragClass='upELement'
          group='column'
          animation={300}
          className='flex h-full w-max gap-10'
          list={iterable(columns)}
          setList={handleSortColumns}
          handle='.notDragAndDrop'
        >
          {columns?.length &&
            columns?.map((col, idx) => (
              <div
                className='column-sortable h-full w-[330px] flex flex-col shrink-0 relative group/columnHeader'
                key={col.id}
              >
                <div className='columnHeader w100% flex items-center gap-2 px-[17px] py-[10px] border border-[#E7EDF1] rounded-[16px] mb-2 bg-[#ECF1F8] relative '>
                  <GripVertical className='handle cursor-grab active:cursor-grabbing shrink-0' size='16px' />
                  <TextArea
                    defaultValue={columns[idx].name}
                    value={columns[idx].name}
                    onChange={(e) => handleInputChange(e, col.id)}
                    placeholder='Название колонны'
                    onListenerBlur={(e) => onColumnSaveName(e, col.id)}
                    enterKey
                    enterDown={() => { }}
                    height={34}
                    spellCheck={false}
                    className='text-md overflow-none bg-transparent ring-offset-0'
                    name='NewColumn'
                  />
                  <span className='p-1 shrink-0 bg-slate-200 size-8 text-center rounded-md' >{columns[idx]?.tasks?.length}</span>
                  <NewTaskButton name={'newTaskInColumnHeader' + col.id} columnId={col.id.toString()} className='left-0 top-[120%] ml-auto shadow-none w-max' classNameNewTask='absolute w-full right-0 top-[110%]' >
                    <Button className='p-2 rounded-[12px] bg-transparent text-slate-300 ml-auto' variant={'outline'}>
                      <Plus size={22} />
                    </Button>
                  </NewTaskButton>
                  <Button className='absolute left-[101%] p-1 group-hover/columnHeader:opacity-100 opacity-0 transition-opacity hover:text-red-400 text-gray-400' variant={'ghost'} onClick={() => {
                    setRemoveColumn(col.id)
                    setRemoveColumnName(col.name)
                  }} >
                    <TrashIcon size={14} />
                  </Button>
                </div>
                <div className='scrollBar flex grow flex-col overflow-y-auto' >
                  <div className={`flex flex-col gap-2 ${columns[idx].tasks?.filter(ca => ca.pinned).length ? 'pb-2' : ''}`} >
                    {columns[idx].tasks?.filter(ca => ca.pinned).map((item) => (
                      <TaskCard
                        key={item.id}
                        openSheet={() => handleOpen(item)}
                        value={item.name}
                        cardData={item}
                        id={item.id.toString()}
                      />
                    ))}
                  </div>
                  <ReactSortable
                    ghostClass='subElement'
                    dragClass='upELement'
                    group='groupName'
                    animation={300}
                    list={iterable(col.tasks.filter(ca => !ca.pinned))}
                    onAdd={moveTaskItemColumn}
                    onUpdate={moveTaskItem}
                    setList={() => { }}
                    handle='.taskCard'
                    id={col.id.toString()}
                    className='flex grow flex-col gap-2 pb-2'
                  >
                    {columns[idx].tasks?.filter(ca => !ca.pinned).map((item) => (
                      <TaskCard
                        key={item.id}
                        openSheet={() => handleOpen(item)}
                        value={item.name}
                        cardData={item}
                        id={item.id.toString()}
                        className='taskCard'
                      />
                    ))}
                  </ReactSortable>
                </div>
              </div>
            ))}
        </ReactSortable>
      </>
      ) : null
      }
      <div className='w-[350px] cursor-pointer text-slate-300 border-dashed border-slate-300 border p-4 h-max rounded-md  flex justify-center items-center flex-shrink-0' onClick={handleAddColumn} >
        <Plus size={32} />
      </div>
      <DialogInput
        text='Введите название колонны'
        onCancel={() => setOpenCreateColumn(false)}
        onSubmit={onSubmit}
        open={openCreateColumn}
      />
      <AlertAnswer
        open={!!removeColumn}
        accept={handleRemoveColumn}
        cancel={() => setRemoveColumn(null)}
        text={`Вы действительно хотите удалить колонну ${removeColumnName}?`}
      />
    </div >
  );
};
